let data = [
  {
    id: 1,
    pid: 1,
    title: "主页",
    children: [
      {
        id: 3,
        pid: 1,
        title: "欢迎",
        children: [
          {
            id: 4,
            pid: 3,
            title: "日志",
            children: [
              {
                id: 5,
                pid: 4,
                title: "测试",
              },
            ],
          },
        ],
      },
    ],
  },
  {
    id: 2,
    pid: 2,
    title: "管理",
  },
];
//树形扁平化
function repeatTree(data) {
  let newArray = [];
  function recursion(data) {
    data.forEach((item) => {
      if (item.children) {
        recursion(item.children);
      }
      newArray.push({
        id: item.id,
        pid: item.pid ?? "",
        title: item.title,
      });
    });
  }
  recursion(data);
  return newArray;
}
let res = repeatTree(data);
console.log(res);
// [
//   { id: 5, pid: 4, title: "测试" },

//   { id: 4, pid: 3, title: "日志" },

//   { id: 3, pid: 1, title: "欢迎" },

//   { id: 1, pid: 1, title: "主页" },

//   { id: 2, pid: 2, title: "管理" },
// ];

//扁平数据树形化
function convertTree(repeatArr) {
  let arr = [];
  //通过pid找id   找父节点
  repeatArr.forEach((item) => {
    // console.log(item);
    let parent = repeatArr.find((v) => v.id === item.pid && item.id != v.id);
    // console.log(parent);
    if (parent) {
      if (!parent.children) {
        parent.children = [];
      }
      parent.children.push(item);
    } else {
      arr.push(item);
    }
  });
  return arr;
}
let sss = convertTree(res);
console.log(sss);
